package com.atguigu.myjuc.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 打印12A34B56C.................
 */
public class PrintDemo {
    public static void main(String[] args) {
        Print print = new Print();

        new Thread(()->{
            for (int i = 0; i < 26; i++) {
                print.printNumber();
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 26; i++) {
                print.printLetter();
            }
        }).start();
    }
}

class Print{
    int count = 1;
    boolean flag = true;

    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    public void printNumber() {
        lock.lock();
        try {
            while (!flag){
                condition.await();
            }
            System.out.print(count++);
            System.out.print(count++);
            flag = false;
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }

    public void printLetter() {
        lock.lock();
        try {
            while (flag){
                condition.await();
            }
            System.out.print((char) ('A'+count/2-1));
            flag = true;
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }
    /*private final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();
    public void printNumber(){
        lock.lock();
        try {
            while (!flag){
                condition.await();
            }
            System.out.print(count++);
            System.out.print(count++);
            flag = false;
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }

    public void printLetter(){
        lock.lock();
        try {
            while (flag){
                condition.await();
            }
            char letter = (char)('A' + count / 2 - 1);
            System.out.print(letter);
            flag = true;
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }*/

}
